package cn.project.lemontree.service.impl;

import cn.project.lemontree.bean.Album;
import cn.project.lemontree.service.AlbumService;
import cn.project.lemontree.dao.AlbumDao;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service("albumService")
public class AlbumServiceimpl extends ServiceImpl<AlbumDao, Album> implements AlbumService {
    @Resource
    AlbumDao albumDao;

    @Override
    public List<Album> listpage(int page, int size, String theme,Integer parentId){
        return albumDao.listpage((page - 1) * size,size,theme,parentId);
    }

    @Override
    public int count(String theme,Integer parentId){
        return albumDao.count(theme,parentId);
    }

    @Override
    public Album findById(Integer albumId){
        return albumDao.findById(albumId);
    }

    @Override
    public boolean save(MultipartFile file,Album album){
        album.setCreateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
                .format(new Date()));
        String vurl = "Albums/" + saveFile(file);
        album.setVurl(vurl);
        return albumDao.save(album) > 0;
    }

    public String saveFile(MultipartFile file){
        List<String> list = new ArrayList<>();
        String fileurl = "";
        String filename = UUID.randomUUID().toString() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));;
        try{
            String filepath = "D://lemontree/Albums";
            File realpath = new File(filepath);
            if(!realpath.exists()){
                boolean mkdirs = realpath.mkdirs();
            }
            file.transferTo(new File(realpath + "/" + filename));
            fileurl = filepath + "/" + filename;
        }catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }

}
